'use strict'
const express = require('express');
const http = require('http');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();

app.use(cookieParser());

const routes = require('./routes/routes');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', require('ejs-mate'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(express.static(path.join(__dirname, 'public'), {maxage: '1y'}));

routes(app);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('页面不存在');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  if(err.status!==404){
    console.error(err);
  }
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = err;//req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json(err);
});

var port = process.env.PORT || 8000;
app.set('port', port);

var server = http.createServer(app);
server.listen(port);
server.on('listening', onListening);

function onListening() {
  var addr = server.address();
  const url = `http://127.0.0.1:${addr.port}/`;
  console.log(`Listening on ${url}`);
}
